# -*- coding: utf-8 -*-
"""
@author: 木头人
@time: 2024/5/16 14:17

pip install pymongo -i https://mirrors.aliyun.com/pypi/simple/

"""
import pymongo
import pymysql
from dbutils.pooled_db import PooledDB  # 3.0以后版本
import threading
from pymongo import MongoClient
from pymongo.database import Database
from pymongo.pool import Pool
from pymongo.mongo_client import MongoClient
from concurrent.futures import ThreadPoolExecutor

MONGO_HOST = "localhost"
MONGO_PORT = 27017
MONGO_USER = "root"
MONGO_PASSWORD = "123456"
MONGO_DATABASE="demo"
MONGO_COLLECTION ="demo"
maxPoolSize=10

class MongoHelper(object):

    def __init__(self):

        self.mongo_uri = f'mongodb://{MONGO_USER}:{MONGO_PASSWORD}@{MONGO_HOST}:{MONGO_PORT}'
        self.client = pymongo.mongo_client.MongoClient(self.mongo_uri,connectTimeoutMS=5000,maxPoolSize=10)
        self.db = self.client[MONGO_DATABASE]
        self.local=threading.local()
        # self.pool=ThreadPoolExecutor(max_workers=10).submit(self.client,self.mongo_uri,connectTimeoutMS=5000)

    def __enter__(self):
        print('====')
        return self.db

    def __exit__(self, exc_type, exc_val, exc_tb):

        pass

    def databases(self):

        print(self.client.list_database_names())

        return self.client.list_database_names()

    def collections(self):

        for name in self.databases():
            print(name,'-----',self.client.get_database(name).list_collection_names())

    def open(self):

        return self.pool

    def close(self):
        self.client.close()

    def fetchone(self):

        # conn = self.open()
        # print(conn)

        for i in self.db.get_collection('demo').find({"author":"鲁迅"}):
            yield i


MHelper=MongoHelper()

# print(MHelper.fetchone())
# for i in MHelper.fetchone():
#     print(i)

# MHelper.collections()
# MHelper.fetchone()
#
# with MHelper as f:
#     print(f)

